package com.ott.Util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.ott.tool.IndexForm;

public class FileUtil {
	/**
     * 递归删除目录下的所有文件及子目录下所有文件
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful.
     *                 If a deletion fails, the method stops attempting to
     *                 delete and returns "false".
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }else if(dir.isFile()){
        	boolean success = dir.delete();
        	 if (!success) {
                 return false;
             }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
    
    public static Boolean copyFile(String oldPath, String newPath) { 
    	Boolean flag = false;
    	try { 
    		int bytesum = 0; 
    		int byteread = 0; 
    		File oldfile = new File(oldPath); 
    		if (oldfile.exists()) { //文件存在时 
	    		InputStream inStream = new FileInputStream(oldPath); //读入原文件 
	    		FileOutputStream fs = new FileOutputStream(newPath); 
	    		byte[] buffer = new byte[1444]; 
	    		while ( (byteread = inStream.read(buffer)) != -1) { 
		    		bytesum += byteread; //字节数 文件大小 
		    		fs.write(buffer, 0, byteread); 
		    		flag = true;
	    		} 
	    			inStream.close(); 
    		} 
		}catch (Exception e) { 
			IndexForm.textArea.append("复制单个文件操作出错\r\n");
    		flag = false;
    		e.printStackTrace(); 

		}
		return flag; 
    }  
}
